from typing import Dict, Union

from conf.config import MYSQL_CONFIG
from db.mysql.mysql_db import MysqlClient


class VideoDAO(object):
    """ 视频数据访问对象 """

    def __init__(self, *args, **kwargs):
        super(VideoDAO, self).__init__(*args, **kwargs)

    @staticmethod
    def get_mysql_conn():
        """ 获取mysql连接 """
        mysql_conn = MysqlClient(MYSQL_CONFIG)
        return mysql_conn

    def get_video_content(self, video_id: int) -> Dict[str, Union[int, str]]:
        """
        获取视频文案
        :param video_id: 视频id
        :return:
        """
        mysql_conn = self.get_mysql_conn()
        video_content = dict()
        try:
            sql = ('SELECT id, content FROM douyin_video '
                   'WHERE id = %s;')
            args = (video_id, )
            video_content = mysql_conn.fetchone(sql, args=args)
        finally:
            if "mysql_conn" in dir():  # 判断连接是否成功创建，创建了才能执行close()
                mysql_conn.close()

        return video_content


def main():
    video_dao = VideoDAO()
    video_content = video_dao.get_video_content(video_id=1)
    if video_content:
        print(video_content.get("content"))


if __name__ == '__main__':
    main()
